import { Column } from '../type';
import { nextTick } from 'vue';

// 创建拖拽指示器
const createResizeProxy = (tableWrapper: HTMLElement | null) => {
  if (!tableWrapper) return null;
  console.log('createResizeProxy')
  // 检查是否已存在拖拽指示器
  let proxy = tableWrapper.querySelector('.table-resize-proxy') as HTMLElement;
  if (!proxy) {
    proxy = document.createElement('div');
    proxy.className = 'table-resize-proxy';
    proxy.style.cssText = `
      position: absolute;
      top: 0;
      bottom: 0;
      width: 2px;
      background-color: red;
      z-index: 9999;
      display: none;
    `;
    tableWrapper.appendChild(proxy);
  }
  return proxy;
};

// 更新列宽
const updateColumnWidth = (th: HTMLElement, newWidth: number, colIndex: number, column: Column) => {
  const table = th.closest('table');
  if (!table) return;

  // 更新表头宽度
  th.style.width = newWidth + 'px';

  // 更新表体中对应列的单元格宽度
  const columnIndex = Array.from(th.parentElement!.children).indexOf(th);
  table.querySelectorAll(`tbody tr td:nth-child(${columnIndex + 1})`).forEach((cell) => {
    if (cell instanceof HTMLElement) {
      cell.style.width = newWidth + 'px';
    }

    // 更新单元格内容的最小宽度
    const content = cell.querySelector('.table__cell-content');
    if (content instanceof HTMLElement) {
      content.style.minWidth = newWidth + 'px';
    }
  });

  // 如果是固定列，需要更新后续固定列的位置
  if (column.fixed === 'left') {
    updateFixedLeftColumnsPosition(table, colIndex, newWidth);
  }

  if (column.fixed === 'right') {
    updateFixedRightColumnsPosition(table, colIndex, newWidth);
  }
};

// 更新左侧固定列的位置
const updateFixedLeftColumnsPosition = (table: Element, resizedColIndex: number, newWidth: number) => {
  const headerCells = table.querySelectorAll('thead th');
  let accumulatedWidth = 30; // 序号列宽度

  // 计算前面固定列的累计宽度
  headerCells.forEach((th, index) => {
    if (index < resizedColIndex && index > 0) {
      // 跳过序号列
      const columnElement = th as HTMLElement;
      if (th.classList.contains('table__fixed-column-left')) {
        accumulatedWidth += columnElement.offsetWidth;
      }
    }
  });

  // 更新当前列之后的左侧固定列位置
  headerCells.forEach((th, index) => {
    if (index > resizedColIndex && th.classList.contains('table__fixed-column-left')) {
      (th as HTMLElement).style.left = accumulatedWidth + 'px';
      accumulatedWidth += (th as HTMLElement).offsetWidth;
    }
  });

  // 更新表体中的固定列位置
  const bodyRows = table.querySelectorAll('tbody tr');
  bodyRows.forEach((row) => {
    const cells = row.querySelectorAll('td');
    let accumulatedWidth = 30; // 序号列宽度

    cells.forEach((td, index) => {
      if (index < resizedColIndex && index > 0) {
        // 跳过序号列
        if (td.classList.contains('table__fixed-column-left')) {
          const cellElement = td as HTMLElement;
          accumulatedWidth += cellElement.offsetWidth;
        }
      }
    });

    cells.forEach((td, index) => {
      if (index > resizedColIndex && td.classList.contains('table__fixed-column-left')) {
        (td as HTMLElement).style.left = accumulatedWidth + 'px';
        accumulatedWidth += (td as HTMLElement).offsetWidth;
      }
    });
  });
};

// 更新右侧固定列的位置
const updateFixedRightColumnsPosition = (table: Element, resizedColIndex: number, newWidth: number) => {
  // 右侧固定列位置更新逻辑
  // 由于右侧固定列使用right定位，需要重新计算位置
  const headerCells = Array.from(table.querySelectorAll('thead th'));
  const reversedHeaderCells = [...headerCells].reverse();

  let accumulatedWidth = 0;
  for (const th of reversedHeaderCells) {
    if (th.classList.contains('table__fixed-column-right')) {
      (th as HTMLElement).style.right = accumulatedWidth + 'px';
      accumulatedWidth += (th as HTMLElement).offsetWidth;
    }
  }

  // 更新表体中的右侧固定列
  const bodyRows = table.querySelectorAll('tbody tr');
  bodyRows.forEach((row) => {
    const cells = Array.from(row.querySelectorAll('td'));
    const reversedCells = [...cells].reverse();

    let accumulatedWidth = 0;
    for (const td of reversedCells) {
      if (td.classList.contains('table__fixed-column-right')) {
        (td as HTMLElement).style.right = accumulatedWidth + 'px';
        accumulatedWidth += (td as HTMLElement).offsetWidth;
      }
    }
  });
};

// 将 initColumnWidths 移到外部并正确导出
export const initColumnWidths = (tableWrapper: HTMLElement | null, columns: Column[]) => {
  nextTick(() => {
    if (tableWrapper) {
      // 创建拖拽指示器
      createResizeProxy(tableWrapper);

      const table = tableWrapper.querySelector('.table');
      if (table) {
        // 设置表头列宽
        const headerCells = table.querySelectorAll('thead th:not(.table__cell-index)');
        headerCells.forEach((th, index) => {
          // 检查是否为操作列
          if (th.classList.contains('table__action-column')) {
            // 操作列不需要设置固定宽度，保持自适应
            // 只需要确保最小宽度
            (th as HTMLElement).style.width = '150px';
            return;
          }

          if (columns[index]) {
            // 使用默认宽度80px，确保不小于最小宽度50px
            const width = Math.max(50, columns[index].width || 80);
            (th as HTMLElement).style.width = width + 'px';
          }
        });

        // 设置表体列宽
        const bodyRows = table.querySelectorAll('tbody tr');
        bodyRows.forEach((row) => {
          const cells = row.querySelectorAll('td:not(.table__cell-index)');
          cells.forEach((td, index) => {
            // 检查是否为操作列
            if (td.classList.contains('table__action-column')) {
              // 操作列不需要设置固定宽度，保持自适应
              // 只需要确保最小宽度
              (td as HTMLElement).style.minWidth = '150px';
              return;
            }

            if (columns[index]) {
              // 使用默认宽度80px，确保不小于最小宽度50px
              const width = Math.max(50, columns[index].width || 80);
              (td as HTMLElement).style.width = width + 'px';

              // 同时设置内容区域的最小宽度
              const content = td.querySelector('.table__cell-content');
              if (content) {
                (content as HTMLElement).style.minWidth = width + 'px';
              }
            }
          });
        });
      }
    }
  });
};

export const resizeFunction = (e: MouseEvent, column: Column, colIndex: number) => {
  e.preventDefault();
  e.stopPropagation();

  const resizer = e.target as HTMLElement;
  const th = resizer.closest('th') as HTMLElement;
  if (!th) return;

  const tableWrapper = th.closest('.table-wrapper') as HTMLElement;
  const resizeProxy = createResizeProxy(tableWrapper);

  const startX = e.pageX;
  const startWidth = th.offsetWidth;
  const tableLeft = th.closest('table')?.getBoundingClientRect().left || 0;
  // 显示拖拽指示器
  if (resizeProxy) {
    resizeProxy.style.display = 'block';
    resizeProxy.style.left = `${startWidth + (th.getBoundingClientRect().left - tableLeft)}px`;
  }
  // 添加拖拽状态类
  if (tableWrapper) {
    tableWrapper.classList.add('dragging');
  }

  const doDrag = (dragEvent: MouseEvent) => {
    const delta = dragEvent.pageX - startX;
    const newWidth = Math.max(50, startWidth + delta);

    // 更新指示器位置而非实际列宽
    if (resizeProxy) {
      resizeProxy.style.left = `${th.getBoundingClientRect().right - tableLeft}px`;
    }
  };

  const stopDrag = () => {
    // 拖拽结束时才更新实际列宽
    if (resizeProxy) {
      const finalLeft = parseInt(resizeProxy.style.left);
      const newWidth = finalLeft - (th.getBoundingClientRect().left - tableLeft);

      // 更新实际列宽
      updateColumnWidth(th, newWidth, colIndex, column);

      // 隐藏指示器
      resizeProxy.style.display = 'none';
    }

    // 移除拖拽状态类
    if (tableWrapper) {
      tableWrapper.classList.remove('dragging');
    }

    document.removeEventListener('mousemove', doDrag);
    document.removeEventListener('mouseup', stopDrag);
  };

  document.addEventListener('mousemove', doDrag);
  document.addEventListener('mouseup', stopDrag);
};

// 添加操作列宽度调整处理函数
export const actionColumnResize = (e: MouseEvent) => {
  e.preventDefault();
  e.stopPropagation();

  const resizer = e.target as HTMLElement;
  const th = resizer.closest('th') as HTMLElement;
  if (!th) return;

  const tableWrapper = th.closest('.table-wrapper') as HTMLElement;
  const resizeProxy = createResizeProxy(tableWrapper);

  const startX = e.pageX;
  const startWidth = th.offsetWidth;
  const tableLeft = th.closest('table')?.getBoundingClientRect().left || 0;
  console.log("fdsafds")
  // 显示拖拽指示器
  if (resizeProxy) {
    resizeProxy.style.display = 'block';
    resizeProxy.style.left = `${startWidth + (th.getBoundingClientRect().left - tableLeft)}px`;
  }

  // 添加拖拽状态类
  if (tableWrapper) {
    tableWrapper.classList.add('dragging');
  }

  const doDrag = (dragEvent: MouseEvent) => {
    const delta = dragEvent.pageX - startX;
    const newWidth = Math.max(150, startWidth + delta);

    // 更新指示器位置
    if (resizeProxy) {
      resizeProxy.style.left = `${th.getBoundingClientRect().left - tableLeft + newWidth}px`;
    }
  };

  const stopDrag = () => {
    // 拖拽结束时才更新实际列宽
    if (resizeProxy) {
      const finalLeft = parseInt(resizeProxy.style.left);
      const newWidth = finalLeft - (th.getBoundingClientRect().left - tableLeft);

      // 更新操作列宽度
      th.style.width = newWidth + 'px';
      th.style.minWidth = newWidth + 'px';

      // 同步更新表体中的操作列宽度
      const table = th.closest('table');
      if (table) {
        table.querySelectorAll('tbody tr td.table__action-column').forEach((td) => {
          if (td instanceof HTMLElement) {
            td.style.width = newWidth + 'px';
            td.style.minWidth = '150px';
          }
        });
      }

      // 隐藏指示器
      resizeProxy.style.display = 'none';
    }

    // 移除拖拽状态类
    if (tableWrapper) {
      tableWrapper.classList.remove('dragging');
    }

    document.removeEventListener('mousemove', doDrag);
    document.removeEventListener('mouseup', stopDrag);
  };

  document.addEventListener('mousemove', doDrag);
  document.addEventListener('mouseup', stopDrag);
};
